﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using MyWeb.ServiceBus.Common;
using MyWeb.ServiceBus.Model.Dto;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services.Db;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.ServiceBus.Services.Impl
{
    internal class GatewayService : BaseEFService<Model.Models.Gateway>, IGatewayService
    {
        Context db;
        public GatewayService(Context context) : base(context)
        {
            db = context;
        }
        public async Task<List<GatewayDto>> QueryPageAsync(GatewayDto dto)
        {
            var where = ExtLinq.True<GatewayDto>();
            if (!string.IsNullOrEmpty(dto.Key))
            {
                where = where.And(o => o.Status.Contains(dto.Key) || o.ServiceUri.Contains(dto.Key) || o.Requst.Contains(dto.Key));
            }

            var linq = db.Gateway
                .Select(a => new GatewayDto
                {
                    Id = a.Id,
                    ServiceId = a.ServiceId,
                    Version = a.Version,
                    Status = a.Status,
                    LoadBalance = a.LoadBalance,
                    ThresholdValue = a.ThresholdValue,
                    IsFusing = a.IsFusing,

                    ServiceType = a.ServiceType,
                    ServiceUri = a.ServiceUri,

                    SignType = a.SignType,
                    Requst = a.Requst,
                    IsMD = a.IsMD,
                    IsCheckTime = a.IsCheckTime,
                    CreateDate = a.CreateDate,
                    CreateUserId = a.CreateUserId,
                    UpdateDate = a.UpdateDate,
                    UpdateUserId = a.UpdateUserId,
                })
                .Where(where);

            var result = new List<GatewayDto>();
            if(dto.Pagination != null)
            {
                dto.Pagination.DataCount = await linq.CountAsync();
                result = await linq.Skip((dto.Pagination.Page - 1) * dto.Pagination.PageSize)
                    .Take(dto.Pagination.PageSize)
                    .ToListAsync();
            }
            else
            {
                result = await linq.ToListAsync();
            }
            return result;
        }
    }
}
